package com.gitee.wsl.time.schedule

import com.gitee.wsl.time.schedule.cron.CronExpression
import com.gitee.wsl.time.schedule.interval.Interval

enum class ScheduleExpressionType {
    CRON_EXPRESSION {
        override fun createSchedule(scheduleExpression: String): AbstractTimeScheduler {
            return CronExpression.create(scheduleExpression)
        }
    },

    INTERVAL {
        override fun createSchedule(scheduleExpression: String): AbstractTimeScheduler {
            return Interval(scheduleExpression)
        }
    };

    abstract fun createSchedule(scheduleExpression: String): AbstractTimeScheduler

    companion object {
        fun getSchedule(scheduleExpression: String): AbstractTimeScheduler {
            if (scheduleExpression.isNotEmpty()) {
                if (scheduleExpression.matches(".*\\s.*".toRegex())) {
                    return CRON_EXPRESSION.createSchedule(scheduleExpression)
                } else if (scheduleExpression.startsWith("P")) {
                    return INTERVAL.createSchedule(scheduleExpression)
                }
            }
            throw ScheduleException(scheduleExpression)
        }
    }
}

fun TimeScheduler.Companion.create(scheduleExpression: String): AbstractTimeScheduler {
    return ScheduleExpressionType.getSchedule(scheduleExpression)
}